package kpu.SmartLibrary;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class DBHandler {
	private DBHelper helper;
	private SQLiteDatabase db;

	private DBHandler(Context ctx) {
		this.helper = new DBHelper(ctx);
		this.db = helper.getWritableDatabase();
	}

	public static DBHandler open(Context ctx) throws SQLException {
		DBHandler handler = new DBHandler(ctx);
		return handler;
	}

	public void close() {
		helper.close();
		db.close();
	}

	public long insert(String book_uid, String book_title, String book_writer) {
		ContentValues values = new ContentValues();
		values.put("uid", book_uid);
		values.put("title", book_title);
		values.put("writer", book_writer);

		return db.insert("book", null, values);
	}

	public Cursor selectUid(String uid) throws SQLException {
		Cursor cursor = db.query(true, "book", new String[] { "uid", "title",
				"writer" }, "uid" + "= \"" + uid + "\"", null, null, null,
				null, null);
		if (cursor != null) {
			cursor.moveToFirst();
		}

		return cursor;
	}

	// public Cursor selectTitle(String title) throws SQLException {
	// Cursor cursor = db.query(true, "book",
	// new String[] {"uid", "title", "writer" },
	// "title" + "like '%" + title+ "%'",
	// null, null, null, null, null);
	// if (cursor != null) { cursor.moveToFirst(); }
	//
	// return cursor;
	// }
	//
	//

	public Cursor selectAll() throws SQLException {
		Cursor cursor = db.query(true, "book", new String[] { "uid", "title",
				"writer" }, null, null, null, null, null, null);

		if (cursor != null) {
			cursor.moveToFirst();
		}

		return cursor;
	}
}
